<script setup>
import { ref, reactive,onMounted } from "vue";
import { ElMessage, ElMessageBox ,ElLoading  } from "element-plus";
import {
  edit_user,
  get_user_list,
  delete_user,
  add_user
} from "../../api/index";
import {useRouter} from "vue-router";
import { SERVER_HOST } from "../../config";


const usersPageTotal = ref(0)
const usersTableData = ref([])
const usersloadingSwicth = ref(false)
const usersQuery = reactive({
  page:0,
  rows:10,
  id:"",
  phone:"",
  nick_name:"",
  sex:"",
  status:""
})

const editQuery = reactive({
  uid: "",
  avatar: "",
  nick_name: "",
  sex: "",
  age: "",
  status: ""
})

const editVisible =ref(false)
const addVisible =ref(false)
const addOrEditFrom = reactive({
  id:"",
  phone:"",
  password:"",
  avatar:"",
  nick_name:"",
  sex:"",
  age:"",
  status:""
})

//控制添加评论弹框
const addUser =()=>{
  addOrEditFrom.id = ''
  addOrEditFrom.phone = ''
  addOrEditFrom.nick_name = ''
  addOrEditFrom.password = ''
  addOrEditFrom.avatar = ''
  addOrEditFrom.sex = ''
  addOrEditFrom.age = ''
  addOrEditFrom.status = ''
  addVisible.value = true
}
//控制编辑弹框
const editUserInfo =(index,row)=>{

  Object.keys(addOrEditFrom).forEach((item) => {
    addOrEditFrom[item] = row[item];
    imgobj.url=row.avatar;
    fileList.value=[]
    fileList.value.push((imgobj))
  });
  if (addOrEditFrom.status===1){
    addOrEditFrom.status="正常"
  }else if (addOrEditFrom.status===0){
    addOrEditFrom.status="暂停使用"
  }
  if (addOrEditFrom.sex===1){
    addOrEditFrom.sex="男"
  }else if (addOrEditFrom.sex===0){
    addOrEditFrom.sex="女"
  }else if (addOrEditFrom.sex===2){
    addOrEditFrom.sex="保密"
  }
  console.log(addOrEditFrom.status)
  editVisible.value = true;
}


let fileList= ref([]);
let imgobj=ref({
  url:""
})
//头像上传
const handleAvatarSuccess=(resource) =>{
  fileList.value=[]
  imgobj.url=resource.data.file_url;
  console.log(imgobj.url)
  fileList.value.push((imgobj))
  console.log(imgobj.url)
  addOrEditFrom.avatar=imgobj.url;
  console.log(addOrEditFrom.avatar)

};
const handleRemove=() =>{
  fileList.value=[]
  addOrEditFrom.avatar = ''
};
const editstart=(file)=>{
  // handleRemove()
}

// 保存编辑
const saveEdit = ()=>{
    if (addOrEditFrom.id === ''){
      ElMessage.warning("用户id不能为空！");
    }else if (addOrEditFrom.phone === '') {
      ElMessage.warning("用户手机号不能为空！");
    }else if (addOrEditFrom.nick_name === ''){
      ElMessage.warning("用户昵称不能为空！");
    }else if (addOrEditFrom.avatar === ''){
      ElMessage.warning("用户头像不能为空！");
    }else if (addOrEditFrom.password === ''){
      ElMessage.warning("用户密码不能为空！");
    } else if (addOrEditFrom.sex === ''){
      ElMessage.warning("用户性别不能为空！");
    } else if (addOrEditFrom.status === ''){
      ElMessage.warning("用户状态不能为空！");
    }else if (addOrEditFrom.age === ''){
      ElMessage.warning("用户年龄不能为空！");
    }else{
      ElMessage.success("通过校验！");
      edit_user(addOrEditFrom).then((res) => {
        var code=res.code
        if (code===200){
          ElMessage.success(''+res.msg);
          addOrEditFrom.id = ''
          addOrEditFrom.phone = ''
          addOrEditFrom.nick_name = ''
          addOrEditFrom.password = ''
          addOrEditFrom.avatar = ''
          addOrEditFrom.sex = ''
          addOrEditFrom.age = ''
          addOrEditFrom.status = ''
          editVisible.value = false;
          refresh()
        }else if(code===401){
          ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
            confirmButtonText: "确定",
            callback: action => {
              router.push('/login')
            }
          });
        }else {
          ElMessage.error(''+res.msg)
        }
      });
    }
}

// 保存添加
const saveAdd = ()=>{
   if (addOrEditFrom.phone === '') {
    ElMessage.warning("用户手机号不能为空！");
  }else if (addOrEditFrom.nick_name === ''){
    ElMessage.warning("用户昵称不能为空！");
  }else if (addOrEditFrom.avatar === ''){
    ElMessage.warning("用户头像不能为空！");
  }else if (addOrEditFrom.password === ''){
    ElMessage.warning("用户密码不能为空！");
  } else if (addOrEditFrom.sex === ''){
    ElMessage.warning("用户性别不能为空！");
  }else if (addOrEditFrom.age === ''){
    ElMessage.warning("用户年龄不能为空！");
  }else{
    ElMessage.success("通过校验！");
    add_user(addOrEditFrom).then((res) => {
      var code=res.code
      if (code===200){
        ElMessage.success(''+res.msg);
        addOrEditFrom.phone = ''
        addOrEditFrom.nick_name = ''
        addOrEditFrom.password = ''
        addOrEditFrom.avatar = ''
        addOrEditFrom.sex = ''
        addOrEditFrom.age = ''
        addVisible.value = false;
        refresh()
      }else if(code===401){
        ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
          confirmButtonText: "确定",
          callback: action => {
            router.push('/login')
          }
        });
      }else {
        ElMessage.error(''+res.msg)
      }
    });
  }
}

// 刷新表格数据
const refresh=()=>{
  usersQuery.id=''
  usersQuery.phone=''
  usersQuery.nick_name=''
  usersQuery.sex=''
  usersQuery.status=''
  getUserData()
}

// 获取表格数据
const getUserData = () => {
  var startTime= new Date().getTime();
  usersloadingSwicth.value=true;
  get_user_list(usersQuery).then((res) => {
        var code = res.code;
        if (code===200){
          usersTableData.value = res.data;
          usersPageTotal.value = res.total || 0;
          console.log(res.data[0].headline)
          var endTime= new Date().getTime();
          ElMessage.success('请求耗时'+(endTime-startTime)+"ms");
          usersloadingSwicth.value=false;
        }else if(code===401){
          ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
            confirmButtonText: "确定",
            callback: action => {
              sessionStorage.clear()
              localStorage.removeItem("user_name");
              localStorage.removeItem("token");
              console.log('用户信息已清除')
              router.push('/login')
            }
          });
        }else{
          usersTableData.value = res.data;
          usersloadingSwicth.value=false;
        }

      }

  );

};
// 删除用户
const remove_user =(index,row)=>{
  console.log('sssssssssssssssssssss')
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  }).then(() => {
    Object.keys(addOrEditFrom).forEach((item) => {
      addOrEditFrom[item] = row[item];
    });
    delete_user(addOrEditFrom).then((res) => {
      var code = res.code;
      var msg = res.msg;
      if (code===200){
        ElMessage.success(""+msg);
      }else if(code===401){
        ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
          confirmButtonText: "确定",
          callback: action => {
            router.push('/login')
          }
        });
      }else {
        ElMessage.error(''+msg);
      }
    });
    //停留200毫秒后刷新页面数据
    setTimeout(() => {
      refresh()
    }, 200);
  }).catch(() => {
    ElMessage.warning("删除取消");
  });
}

// 获取视口高度
const screenHeight = window.innerHeight-290;

const errorHandler = () => true


const  usersHandlePageChange= (val)=>{
  usersQuery.page = val-1;
  getUserData();
}

const usersHandleSizeChange=(val)=>{
  usersQuery.rows = val;
  getUserData();
}


onMounted(()=>{
  getUserData()
})
</script>



<template>
  <div>
    <div class="container"  >
      <div class="handle-box" >
        <el-input v-model="usersQuery.id" placeholder="用户id" clearable class="handle-input mr10"></el-input>
        <el-input v-model="usersQuery.phone"  placeholder="手机号" clearable class="handle-input mr10"></el-input>
        <el-input v-model="usersQuery.nick_name" placeholder="用户昵称" clearable class="handle-input mr10"></el-input>
        <el-select v-model="usersQuery.sex" placeholder="性别" clearable class="handle-select mr10">
          <el-option key="2" label="保密" value="2"></el-option>
          <el-option key="1" label="男" value="1"></el-option>
          <el-option key="0" label="女" value="0"></el-option>
        </el-select>
        <el-select v-model="usersQuery.status" placeholder="用户状态" clearable class="handle-select mr10">
          <el-option key="1" label="正常" value="1"></el-option>
          <el-option key="0" label="暂停使用" value="0"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="getUserData" >搜索</el-button>
        <el-button type="success" @click="addUser" icon="el-icon-circle-plus-outline" >添加用户</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh" >刷新</el-button>
      </div>
      <el-table :data="usersTableData" v-loading="usersloadingSwicth"  element-loading-text="拼命加载中..." element-loading-background="rgba(250,250,250,0.97)" border class="table" :height="screenHeight"  ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column  prop="id" label="用户id"  width="120px"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="120px">
          <template #default="scope">
            <el-text >{{ scope.row.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') }}</el-text>

          </template>
        </el-table-column>
        <el-table-column label="用户头像" width="150px" align="center">
          <template #default="scope">
            <el-avatar
                :src="scope.row.avatar"
            />
          </template>
        </el-table-column>

        <el-table-column prop="nick_name" label="用户昵称"></el-table-column>
        <el-table-column prop="sex" label="性别" width="80px">
          <template #default="scope">
            <el-tag  :type="scope.row.sex===1?'primary':scope.row.sex===0?'danger':'warning'" effect="dark">
              {{ scope.row.sex===1?'男':scope.row.sex===0?'女':'保密' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80px"></el-table-column>
        <el-table-column prop="password" label="密码" width="200px">
          <template #default="scope">
            <div style="display: flex;flex-direction: row;align-items: center; justify-content: space-between;  ">
              <el-text >{{scope.row.password_show?scope.row.password:'**********' }}</el-text>
              <el-button style="padding-right:30px;" type="text" icon="el-icon-view" @click="scope.row.password_show = !scope.row.password_show"  ></el-button>
            </div>

          </template>
        </el-table-column>

        <el-table-column  label="用户状态" align="center">
          <template #default="scope">
            <el-tag  :type="scope.row.status===1?'success':'danger'" effect="dark">{{scope.row.status===1?'正常':'暂停使用'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="register_time" label="注册时间"></el-table-column>


        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="editUserInfo(scope.$index, scope.row)" >编辑 </el-button>
            <el-button type="text" icon="el-icon-delete" class="red" @click="remove_user(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--   编辑框      -->
      <el-dialog title="编辑用户信息" v-model="editVisible" width="35%">
        <el-form label-width="70px">
          <el-form-item label="用户id" width="50%">
            <el-input v-model="addOrEditFrom.id" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="手机号" width="50%">
            <el-input v-model="addOrEditFrom.phone" ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" width="50%">
            <el-input v-model="addOrEditFrom.nick_name" ></el-input>
          </el-form-item>
          <el-form-item label="用户头像" >
            <div style="display: flex; flex-direction: row; align-items: center;">
              <el-avatar :src="addOrEditFrom.avatar" @error="errorHandler" :size="150">
                <img
                    src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                />
              </el-avatar>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <el-upload
                  :action="SERVER_HOST+'/fileInfo'"
                  list-type="picture-card"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :file-list="fileList"
                  :on-remove="handleRemove"
                  :on-change="editstart">
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>

          </el-form-item>
          <el-form-item label="密码" width="50%">
            <el-input type="password"  show-password v-model="addOrEditFrom.password" ></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="addOrEditFrom.sex"   class="handle-select mr10">
              <el-option key="1" label="男" value="男"></el-option>
              <el-option key="0" label="女" value="女"></el-option>
              <el-option key="2" label="保密" value="保密"></el-option>
            </el-select>
            <el-tag  :type="addOrEditFrom.sex==='男'?'primary':addOrEditFrom.sex==='女'?'danger':'warning'" effect="dark">
              {{ addOrEditFrom.sex}}</el-tag>
          </el-form-item>
          <el-form-item label="年龄" width="50%">
            <el-input v-model="addOrEditFrom.age" ></el-input>
          </el-form-item>
          <el-form-item label="用户状态">
            <el-select v-model="addOrEditFrom.status" placeholder="状态" class="handle-select mr10">
              <el-option key="1" label="正常" value="1"></el-option>
              <el-option key="0" label="暂停使用" value="0"></el-option>
            </el-select>
            <el-tag  :type="addOrEditFrom.status==='正常'?'success':'danger'" effect="dark">
              {{ addOrEditFrom.status==='正常'?'正常':'暂停使用' }}</el-tag>
          </el-form-item>
        </el-form>
        <template #footer >
                <span class="dialog-footer" >
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">保存</el-button>
                </span>
        </template>
      </el-dialog>

      <!--   添加框      -->
      <el-dialog title="添加用户信息" v-model="addVisible" width="35%">
        <el-form label-width="70px">
          <el-form-item label="手机号"  width="50%">
            <el-input placeholder="请输入手机号" v-model="addOrEditFrom.phone" ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称"  width="50%">
            <el-input placeholder="请输入昵称" v-model="addOrEditFrom.nick_name" ></el-input>
          </el-form-item>
          <el-form-item label="用户头像" >
            <div style="display: flex; flex-direction: row; align-items: center;">
              <el-avatar :src="addOrEditFrom.avatar" @error="errorHandler" :size="150">
                <img
                    src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                />
              </el-avatar>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <el-upload
                  :action="SERVER_HOST+'/fileInfo'"
                  list-type="picture-card"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :file-list="fileList"
                  :on-remove="handleRemove"
                  :on-change="editstart">
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>

          </el-form-item>
          <el-form-item label="密码"  width="50%">
            <el-input type="password" placeholder="请输入密码" show-password v-model="addOrEditFrom.password" ></el-input>
          </el-form-item>
          <el-form-item label="性别" >
            <el-select v-model="addOrEditFrom.sex" placeholder="请选择性别"  class="handle-select mr10">
              <el-option key="1" label="男" value="男"></el-option>
              <el-option key="0" label="女" value="女"></el-option>
              <el-option key="2" label="保密" value="保密"></el-option>
            </el-select>
            <el-tag v-show="addOrEditFrom.sex"  :type="addOrEditFrom.sex==='男'?'primary':addOrEditFrom.sex==='女'?'danger':'warning'" effect="dark">
              {{ addOrEditFrom.sex}}</el-tag>
          </el-form-item>
          <el-form-item label="年龄"  width="50%">
            <el-input placeholder="请输入年龄" v-model="addOrEditFrom.age" ></el-input>
          </el-form-item>
        </el-form>
        <template #footer >
                <span class="dialog-footer" >
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveAdd">保存</el-button>
                </span>
        </template>
      </el-dialog>


      <div class="pagination">
        <el-pagination background layout="total, prev, sizes, pager, next,jumper"
                       :current-page="usersQuery.page+1"
                       :page-size="usersQuery.rows"
                       :total="usersPageTotal"
                       :page-sizes="[5, 10, 20, 50, 100]"
                       @current-change="usersHandlePageChange"
                       @size-change="usersHandleSizeChange">

        </el-pagination>
      </div>

    </div >


  </div>

</template>



<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.container {
  padding: 30px;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  height:100%;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 240px;
  display: inline-block;
}
.table {
  width: 100%;
  height:100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 5px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.el-upload-list--picture-card .el-upload-list__item {
  overflow: hidden;
  border-radius: 50%;
  border: none;
}

.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.el-upload-list__item img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
body{
  height:100%;
}
</style>